let arr = [];
let flag = 0
const initData = async () => {
    for (let index = 0; index < 1000; index++) {
        flag = (index + 1) * 300
        await getData(index, 300);
        console.log("===================爬取轮训==========" + (index + 1) + "次+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        console.log("爬取数据条数" + arr.length);
        document.getElementById("app").innerText = JSON.stringify(arr.length)
        if (flag != arr.length) {
            console.log("总条数为" + arr.length + "终端终止")
            return saveJsFile(JSON.stringify(arr), 'myScript.json');
        }
    }
    log(arr)
};

/**
 * size 不大于300
 */
const getData = async (page, size) => {
    let data = {
        modelName: "PerfumeGridGallery", limit: size, paginationInfo: {
            type: "latestPerfumeReleases",
        }, sort: "news", page: page, filters: {
            discontinued: "yes",
        }, lang: "zh",
    };

    const response = await fetch("https://web-api-v3.wikiparfum.com/api/dynamic/pagination", {
        method: "POST", headers: {
            "Content-Type": "application/json",
        }, body: JSON.stringify(data),
    });

    if (!response.ok) {
        // 处理错误情况
        // console.error("Error fetching data:", response.statusText);
        return;
    }

    const res = await response.json();
    // console.log(res);
    let res_ = res.results.fragrances
    res_.forEach(el => {
        let ingredients = el.ingredients;//原料
        let ingredientList = []
        ingredients.forEach(ingredient => {
            let image1 = ingredient.image1
            let ing = {
                name: ingredient.name,
            }
            try {
                if (image1.urls) {
                    ing.img = image1.urls.mid
                }
            } catch (e) {
                console.log(e)
            }
            ingredientList.push(ing)
        })
        let data_ = {
            name: el.name, brand: el.brand, year: el.year,//年份
            mouth: el.mouth, img: el.image.urls.mid,//香水图片,
            family: el.family.name,//家族
            familyImg: el.family.image.urls.mid,//家族图片
            secondFamily: el.secondaryFamily.name,//亚科
            ingredients: ingredientList,//原料列表
            sex_: el.gender == "U" ? "中性" : el.gender == "F" ? "女" : "男"
        }
        arr.push(data_);
    })
};

initData();

const saveJsFile = (jsCode, fileName = 'script.json') => {
    // 创建一个 Blob 对象，包含 JavaScript 代码
    const blob = new Blob([jsCode], {type: 'application/javascript'});

    // 创建一个下载链接
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob); // 使用 Blob 创建 URL
    link.download = fileName; // 指定下载文件的名称

    // 模拟点击下载链接
    link.click();

    // 释放 URL 对象
    URL.revokeObjectURL(link.href);
};

